// pages/profile/common-visitors.js
const api = require('../../utils/api').default

Page({
  data: {
    visitorList: [],
    searchKeyword: '',
    page: 1,
    limit: 20,
    total: 0,
    loading: false,
    refreshing: false,
    hasMore: true,
    showModal: false,
    modalTitle: '新增观众',
    formData: {
      name: '',
      id_type: '身份证',
      id_number: '',
      phone: ''
    },
    editId: null,
    idTypeOptions: ['身份证', '护照', '港澳通行证', '台湾通行证'],
    idTypeIndex: 0
  },

  onLoad() {
    this.loadVisitors()
  },

  onShow() {
    // 页面显示时刷新数据
    if (this.data.visitorList.length > 0) {
      this.onRefresh()
    }
  },

  // 加载观众列表
  async loadVisitors(loadMore = false) {
    if (this.data.loading) return

    this.setData({ loading: true })
    
    try {
      const page = loadMore ? this.data.page + 1 : 1
      const params = {
        page,
        limit: this.data.limit,
        keyword: this.data.searchKeyword
      }

      // 注意：api.visitors.getList 已返回 data 对象
      const data = await api.visitors.getList(params)

      const newList = data.list || []
      const total = data.pagination?.total || 0
      
      this.setData({
        visitorList: loadMore ? [...this.data.visitorList, ...newList] : newList,
        total,
        page,
        hasMore: newList.length >= this.data.limit,
        loading: false,
        refreshing: false
      })
    } catch (error) {
      console.error('加载观众列表失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
      this.setData({ loading: false, refreshing: false })
    }
  },

  // 下拉刷新
  onRefresh() {
    this.setData({ refreshing: true, page: 1, hasMore: true })
    this.loadVisitors()
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadVisitors(true)
    }
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({ searchKeyword: e.detail.value })
  },

  // 搜索
  onSearch() {
    this.setData({ page: 1, hasMore: true })
    this.loadVisitors()
  },

  // 新增观众
  addVisitor() {
    this.setData({
      showModal: true,
      modalTitle: '新增观众',
      editId: null,
      formData: {
        name: '',
        id_type: '身份证',
        id_number: '',
        phone: ''
      },
      idTypeIndex: 0
    })
  },

  // 编辑观众
  editVisitor(e) {
    const id = e.currentTarget.dataset.id
    const visitor = this.data.visitorList.find(item => item.id === id)
    
    if (visitor) {
      const idTypeIndex = this.data.idTypeOptions.findIndex(type => type === visitor.id_type)
      this.setData({
        showModal: true,
        modalTitle: '编辑观众',
        editId: id,
        formData: {
          name: visitor.name,
          id_type: visitor.id_type,
          id_number: visitor.id_number || '',
          phone: visitor.phone || ''
        },
        idTypeIndex: idTypeIndex >= 0 ? idTypeIndex : 0
      })
    }
  },

  // 删除观众
  deleteVisitor(e) {
    const id = e.currentTarget.dataset.id
    const name = e.currentTarget.dataset.name

    wx.showModal({
      title: '确认删除',
      content: `确定要删除「${name}」的观众信息吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            // 成功会 resolve，不必判断 result.success
            await api.visitors.delete(id)
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            })
            this.onRefresh()
          } catch (error) {
            console.error('删除观众失败:', error)
            wx.showToast({
              title: '删除失败',
              icon: 'error'
            })
          }
        }
      }
    })
  },

  // 证件类型选择
  onIdTypeChange(e) {
    const index = e.detail.value
    this.setData({
      idTypeIndex: index,
      'formData.id_type': this.data.idTypeOptions[index]
    })
  },

  // 保存观众信息
  async saveVisitor(e) {
    const formData = e.detail.value
    
    // 验证必填字段
    if (!formData.name.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    }
    // 验证手机号格式
    if (formData.phone && !/^1[3-9]\d{9}$/.test(formData.phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }
    // 验证身份证号格式
    if (formData.id_number && formData.id_type === '身份证') {
      const idReg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      if (!idReg.test(formData.id_number)) {
        wx.showToast({
          title: '请输入正确的身份证号',
          icon: 'none'
        })
        return
      }
    }

    try {
      wx.showLoading({ title: '保存中...' })

      if (this.data.editId) {
        await api.visitors.update(this.data.editId, formData)
      } else {
        await api.visitors.create(formData)
      }

      wx.showToast({
        title: this.data.editId ? '更新成功' : '添加成功',
        icon: 'success'
      })
      this.closeModal()
      this.onRefresh()
    } catch (error) {
      console.error('保存观众信息失败:', error)
      wx.showToast({
        title: '保存失败',
        icon: 'error'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 关闭弹窗
  closeModal() {
    this.setData({ showModal: false })
  }
})